package com.example.tools

import android.accessibilityservice.AccessibilityService
import android.annotation.TargetApi
import android.app.Activity
import android.app.Application
import android.content.Context
import android.content.Intent
import android.graphics.PixelFormat
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.provider.Settings.SettingNotFoundException
import android.text.TextUtils.SimpleStringSplitter
import android.view.Gravity
import android.view.View
import android.view.WindowManager
import android.view.accessibility.AccessibilityNodeInfo
import android.widget.Toast
import androidx.core.app.ActivityCompat.startActivityForResult
import androidx.core.content.ContextCompat.startActivity

object Utils {
    /**
     * 检测是否有开启无障碍功能
     */
    fun isAccessibilitySettingsOn(
        mContext: Context,
        clazz: Class<out AccessibilityService?>
    ): Boolean {
        var accessibilityEnabled = 0
        val service = mContext.packageName + "/" + clazz.canonicalName
        try {
            accessibilityEnabled = Settings.Secure.getInt(
                mContext.applicationContext.contentResolver,
                Settings.Secure.ACCESSIBILITY_ENABLED
            )
        } catch (e: SettingNotFoundException) {
            e.printStackTrace()
        }
        val mStringColonSplitter = SimpleStringSplitter(':')
        if (accessibilityEnabled == 1) {
            val settingValue = Settings.Secure.getString(
                mContext.applicationContext.contentResolver,
                Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES
            )
            if (settingValue != null) {
                mStringColonSplitter.setString(settingValue)
                while (mStringColonSplitter.hasNext()) {
                    val accessibilityService = mStringColonSplitter.next()
                    if (accessibilityService.equals(service, ignoreCase = true)) {
                        return true
                    }
                }
            }
        }
        return false
    }

    /**
     * 启动对应包名App
     */
    fun openOtherApp(context: Application, pkg: String) {
        val intent: Intent = context.packageManager.getLaunchIntentForPackage(pkg)!!
        startActivity(context, intent, null)
    }

    const val DDpkg = "com.alibaba.android.rimet";

    /**
     * 打开设置界面的无障碍功能
     */
    fun openSettingAccessibility(context: Context) {
        val intent = Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS)
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        startActivity(context, Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS), null)
    }


    /**
     * 检测是开启悬浮窗
     */
    fun checkOverlayPermission(context: Activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!Settings.canDrawOverlays(context)) {
                startActivityForResult(
                    context,
                    Intent(
                        Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                        Uri.parse("package:" + context.getPackageName())
                    ).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
                    200,
                    null
                )
                Toast.makeText(context, "请先授予 \"栈顶通\" 悬浮窗权限", Toast.LENGTH_LONG).show()
            }
        }
    }

    /**
     * 模拟点击,根据控件id进行模拟点击
     */
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
    fun onClickBtn(ac: AccessibilityService, btn: String) {
        val nodeInfo: AccessibilityNodeInfo = ac.getRootInActiveWindow()
        if (nodeInfo != null) {
            val list = nodeInfo.findAccessibilityNodeInfosByViewId(btn)
            nodeInfo.recycle()
            for (item in list) {
                item.performAction(AccessibilityNodeInfo.ACTION_CLICK)
            }
        }
    }

    fun setWindowManagerAddView(v: View,context: Context) {
        val windowManager =
            context.applicationContext.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val windowManagerParams = WindowManager.LayoutParams(
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.WRAP_CONTENT,
            0, 0,
            PixelFormat.TRANSLUCENT
        )
        // flag 设置 Window 属性
        windowManagerParams.flags =  WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL or WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
        // type 设置 Window 类别（层级）
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//6.0
            //大于6.0使用这个权限，
            windowManagerParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            windowManagerParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
        }
        windowManagerParams.gravity = Gravity.TOP and Gravity.LEFT
        windowManager.addView(v, windowManagerParams)
    }

}
